package com.xkcoding.orm.mybatis.plus.generator.controller;

import cn.hutool.core.date.StopWatch;
import cn.hutool.json.JSONUtil;
import com.xkcoding.orm.mybatis.plus.generator.entity.User;
import com.xkcoding.orm.mybatis.plus.generator.service.UserService;
import dto.QueryDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
  * @Description:描述
  * @Version v1.0.0
  * @author Administrator
  * @date 2022/5/23 14:12
  */
@RestController
@Slf4j
public class IndexController {

    @Resource
    private UserService userService;

    @PostMapping("queryByCondition")
    public ResponseEntity<User> queryByCondition(@Valid @RequestBody QueryDto queryDto) throws InterruptedException {
        StopWatch stopWatch=new StopWatch();
        stopWatch.start();
        log.info("查询用户信息：{}", JSONUtil.parse(queryDto).toString());
        User user = userService.queryByCondition(queryDto);
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
        log.info("查询用户信息耗时：{}", stopWatch.getTotalTimeSeconds());
        return ResponseEntity.ok(user);
    }

    @PostMapping("queryByConditionAsync")
    public ResponseEntity<User> queryByConditionAsync(@Valid @RequestBody QueryDto queryDto) throws InterruptedException, ExecutionException {
        StopWatch stopWatch=new StopWatch();
        stopWatch.start();
        log.info("查询用户信息：{}", JSONUtil.parse(queryDto).toString());
        CompletableFuture<User> supplyAsync = CompletableFuture.supplyAsync(() -> {
            User user = userService.queryByCondition(queryDto);
            return user;
        });
        TimeUnit.SECONDS.sleep(2);
        User user = supplyAsync.get();
        stopWatch.stop();
        log.info("查询用户信息耗时：{}", stopWatch.getTotalTimeSeconds());
        return ResponseEntity.ok(user);
    }

    public static void main(String[] args) {
        final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        final int activeThreadCount = forkJoinPool.getActiveThreadCount();
        log.info("活动线程：--------"+activeThreadCount);
        final int i1 = Runtime.getRuntime().availableProcessors();
        log.info("机器线程：--------"+i1);

        try {
            for (int i = 0; i < 100; i++) {
                forkJoinPool.submit(()->{
                    log.info("打印：");
                });
            }
        } catch (Exception e){
            log.info("主线程捕获异常：--------");
        }
        log.info("执行主线程逻辑");
    }


}
